package com.oa.order.dto;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

import com.oa.order.entity.Order;

public class OrderQueryDTO {
	private String userName;
	private String departmentName;
	private Date startTime;
	private Date endTime;
	private String state;
	
	public String getUserName() {
		return userName;
	}
	public String getDepartmentName() {
		return departmentName;
	}
	@DateTimeFormat(iso=ISO.DATE)
	public Date getStartTime() {
		return startTime;
	}
	@DateTimeFormat(iso=ISO.DATE)
	public Date getEndTime() {
		return endTime;
	}
	public String getState() {
		return state;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}
	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}
	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}
	
	
	public OrderQueryDTO() {
		super();
	}
	public OrderQueryDTO(String userName, String departmentName, Date startTime, Date endTime) {
		super();
		this.userName = userName;
		this.departmentName = departmentName;
		this.startTime = startTime;
		this.endTime = endTime;
		
	}
	public void setState(String state) {
		this.state = state;
	}
	public static Specification<Order> getWhereClause(final OrderQueryDTO condetion){
		return new Specification<Order>() {
			@Override
			public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> pList =  new ArrayList<Predicate>();
				if(condetion.getUserName()!=null && condetion.getUserName().trim().length()>0) {
					Predicate p1 = cb.like(root.get("userName").as(String.class) , "%"+condetion.getUserName()+"%");
					pList.add(p1);
				}
				if(condetion.getDepartmentName()!=null && condetion.getDepartmentName().trim().length()>0) {
					Predicate p2 = cb.like(root.get("departmentName").as(String.class) , "%"+condetion.getDepartmentName()+"%");
					pList.add(p2);
				}
				if(condetion.getStartTime()!=null && condetion.getEndTime()!=null) {
					Predicate p3 = cb.between(root.get("approvalTime").as(Date.class) , condetion.getStartTime(),condetion.getEndTime());
					pList.add(p3);
				}
				
				Predicate p4 = cb.like(root.get("state").as(String.class),"已通过");
				pList.add(p4);
				
				Predicate[] pArray = new Predicate[pList.size()];
				return cb.and(pList.toArray(pArray));
			}
		};	
	}

}
